package com.zzl.study.nacos.registry;

import com.alibaba.nacos.api.naming.PreservedMetadataKeys;
import com.zzl.study.nacos.properties.NacosMultiDiscoveryProperties;
import jakarta.annotation.PostConstruct;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.discovery.ManagementServerPortUtils;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

import java.net.URI;
import java.util.List;
import java.util.Map;

/**
 * Nacos多注册中心注册信息
 *
 * @author: zhangzl
 * @date: 2025/7/15 14:15
 * @version: 1.0
 */
public class NacosMultiRegistration implements Registration {

    /**
     * 管理端点基础路径
     */
    public static final String MANAGEMENT_ENDPOINT_BASE_PATH = "management.endpoints.web.base-path";

    /**
     * 管理端点端口
     */
    public static final String MANAGEMENT_PORT = "management.port";

    /**
     * 管理端点Servlet上下文路径
     */
    public static final String MANAGEMENT_SERVER_SERVLET_CONTEXT_PATH = "management.server.servlet.context-path";

    /**
     * 管理端点上下文路径
     */
    public static final String MANAGEMENT_CONTEXT_PATH = "management.context-path";

    /**
     * 管理端点服务端地址
     */
    public static final String MANAGEMENT_SERVER_ADDRESS = "management.server.address";

    /**
     * 管理端点地址
     */
    public static final String MANAGEMENT_ADDRESS = "management.address";

    /**
     * Nacos多注册中心注册信息自定义工具集合
     */
    private final List<NacosMultiRegistrationCustomizer> registrationCustomizers;

    /**
     * Nacos多注册中心注册配置
     */
    private final NacosMultiDiscoveryProperties nacosMultiDiscoveryProperties;

    /**
     * Spring应用上下文
     */
    private final ApplicationContext context;

    /**
     * 构造函数
     *
     * @param registrationCustomizers       Nacos多注册中心注册信息自定义工具集合
     * @param nacosMultiDiscoveryProperties Nacos多注册中心注册配置
     * @param context                       Spring应用上下文
     */
    public NacosMultiRegistration(List<NacosMultiRegistrationCustomizer> registrationCustomizers, NacosMultiDiscoveryProperties nacosMultiDiscoveryProperties, ApplicationContext context) {
        this.registrationCustomizers = registrationCustomizers;
        this.nacosMultiDiscoveryProperties = nacosMultiDiscoveryProperties;
        this.context = context;
    }

    /**
     * 初始化
     */
    @PostConstruct
    public void init() {
        Map<String, String> metadata = this.nacosMultiDiscoveryProperties.getMetadata();
        Environment env = context.getEnvironment();
        String endpointBasePath = env.getProperty(MANAGEMENT_ENDPOINT_BASE_PATH);
        if (StringUtils.hasLength(endpointBasePath)) {
            metadata.put(MANAGEMENT_ENDPOINT_BASE_PATH, endpointBasePath);
        }
        Integer managementPort = ManagementServerPortUtils.getPort(context);
        if (null != managementPort) {
            metadata.put(MANAGEMENT_PORT, managementPort.toString());
            String contextPath = env.getProperty(MANAGEMENT_SERVER_SERVLET_CONTEXT_PATH);
            String address = env.getProperty(MANAGEMENT_SERVER_ADDRESS);
            if (StringUtils.hasLength(contextPath)) {
                metadata.put(MANAGEMENT_CONTEXT_PATH, contextPath);
            }
            if (StringUtils.hasLength(address)) {
                metadata.put(MANAGEMENT_ADDRESS, address);
            }
        }
        if (null != this.nacosMultiDiscoveryProperties.getHeartBeatInterval()) {
            metadata.put(PreservedMetadataKeys.HEART_BEAT_INTERVAL, this.nacosMultiDiscoveryProperties.getHeartBeatInterval().toString());
        }
        if (null != this.nacosMultiDiscoveryProperties.getHeartBeatTimeout()) {
            metadata.put(PreservedMetadataKeys.HEART_BEAT_TIMEOUT, this.nacosMultiDiscoveryProperties.getHeartBeatTimeout().toString());
        }
        if (null != this.nacosMultiDiscoveryProperties.getIpDeleteTimeout()) {
            metadata.put(PreservedMetadataKeys.IP_DELETE_TIMEOUT, this.nacosMultiDiscoveryProperties.getIpDeleteTimeout().toString());
        }
        customize(registrationCustomizers);
    }

    @Override
    public String getServiceId() {
        return this.nacosMultiDiscoveryProperties.getService();
    }

    @Override
    public String getHost() {
        return this.nacosMultiDiscoveryProperties.getIp();
    }

    @Override
    public int getPort() {
        return this.nacosMultiDiscoveryProperties.getPort();
    }

    public void setPort(int port) {
        this.nacosMultiDiscoveryProperties.setPort(port);
    }

    @Override
    public boolean isSecure() {
        return this.nacosMultiDiscoveryProperties.isSecure();
    }

    @Override
    public URI getUri() {
        return DefaultServiceInstance.getUri(this);
    }

    @Override
    public Map<String, String> getMetadata() {
        return this.nacosMultiDiscoveryProperties.getMetadata();
    }

    public boolean isRegisterEnabled() {
        return this.nacosMultiDiscoveryProperties.isRegisterEnabled();
    }

    public String getCluster() {
        return this.nacosMultiDiscoveryProperties.getClusterName();
    }

    public float getRegisterWeight() {
        return this.nacosMultiDiscoveryProperties.getWeight();
    }

    public NacosMultiDiscoveryProperties getNacosMultiDiscoveryProperties() {
        return this.nacosMultiDiscoveryProperties;
    }

    @Override
    public String toString() {
        return "NacosMultiRegistration{" + "nacosMultiDiscoveryProperties=" + this.nacosMultiDiscoveryProperties + '}';
    }

    /**
     * 自定义注册信息
     *
     * @param registrationCustomizers 自定义工具集合
     */
    protected void customize(List<NacosMultiRegistrationCustomizer> registrationCustomizers) {
        if (registrationCustomizers != null) {
            for (NacosMultiRegistrationCustomizer customizer : registrationCustomizers) {
                customizer.customize(this);
            }
        }
    }

}
